﻿using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderUnpickupingWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderUnpickupingWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderUnpickupingConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                order = ctx.ApptOrders.Where(x => x.Id == orderId)
                    .Select(x => new OrderSummary
                    {
                        Id = x.Id,
                        OrderNo = x.OrderNo,
                        CardNo = x.CardNo,
                        PeriodId = x.Sqno,
                        ClinicSeq = x.VisitNo,
                        TradeNo = x.WxTransactionId,
                        SumFee = x.SumFee
                    }).FirstOrDefault();
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            }

            DataBaseCommandFactory.CreateDatbaseCommand()
            .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.微信退号中.ToInt32());
            //执行退号操作
            var unpickupRequest = new CancelOrderRequest();
            unpickupRequest.FlowNo = order.ClinicSeq;

            CancelOrderResponse unpickupResponse;

                try
                {
                    var httpClient = InHttpClient.GetClient();
                    var responseMsg = httpClient.PostAsJsonAsync("HisSp/CancelOrder", unpickupRequest).Result;
                    responseMsg.EnsureSuccessStatusCode();
                    unpickupResponse = responseMsg.Content.ReadAsAsync<CancelOrderResponse>().Result;
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用院内退号Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    // RMQ 执行退号结果查询
                    var unpickupingChkProducer = new OrderUnpickupingChkProducer();
                    unpickupingChkProducer.Publish(new OrderUnpickupingChkMsg
                    {
                        OrderType = Rmq.Center.OrderType.挂号订单,
                        OrderId = order.Id
                    });

                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }

            if (unpickupResponse.ResultCode != "0")
            {

                DataBaseCommandFactory.CreateDatbaseCommand()
                    .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.取号成功.ToInt32());

                // RMQ 发送退号失败的用户通知
                var msgProducer = new UserMessageProducer();
                msgProducer.Publish(new UserMessageMsg
                {
                    Type = UserMessageType.退号失败通知,
                    OrderId = order.Id
                });
            }
            else
            {
                DataBaseCommandFactory.CreateDatbaseCommand()
                    .UpdateOrderStatus(orderId, ApptOrderExtensions.OrderStatus.微信退号成功.ToInt32());

                // RMQ 发送退号成功的用户通知
                var msgProducer = new UserMessageProducer();
                msgProducer.Publish(new UserMessageMsg
                {
                    Type = UserMessageType.退号成功通知,
                    OrderId = order.Id
                });

                if (order.SumFee > 0)
                {
                    // RMQ 执行退费操作
                    var refundingProducer = new OrderRefundingUnpickupSucceedProducer();
                    refundingProducer.Publish(new OrderRefundingUnpickupSucceedMsg
                    {
                        OrderType = Rmq.Center.OrderType.挂号订单,
                        OrderId = order.Id
                    });
                }
            }


            return new ConsumedResult
            {
                Ack = true
            };
        }

        public class OrderSummary
        {
            public int Id { get; set; }
            public string OrderNo { get; set; }
            public string CardNo { get; set; }
            public string PeriodId { get; set; }
            public string ClinicSeq { get; set; }
            public string TradeNo { get; set; }
            public decimal? SumFee { get; set; }
        }
    }
}